import {Node, tween, Vec2, Vec3} from "cc";
import _ from 'lodash';

// 二阶贝塞尔工具类
export class TweenUtils {
    public static bezierTo(
        target: Node,
        duration: number,
        startPos: Vec2,   // 起点
        controlPoint: Vec2, // 控制点
        endPos: Vec3,     // 终点
        opts?: any
    ) {
        const twoBezier = (t: number) => {
            const x = (1 - t) ** 2 * startPos.x + 2 * t * (1 - t) * controlPoint.x + t ** 2 * endPos.x;
            const y = (1 - t) ** 2 * startPos.y + 2 * t * (1 - t) * controlPoint.y + t ** 2 * endPos.y;
            return new Vec3(x, y, 0);
        };

        return tween(target)
            .tag(1000)
            .to(duration, {}, {
                onUpdate: (_, ratio: number) => {
                    target.worldPosition = twoBezier(ratio);
                },
                ...opts
            });
    }
}

export class RandomUtils {

    public static randomInPool<T>(poolItem: Array<T>, min: number, max: number): Array<T> {
        const shuffled = _(poolItem).shuffle().value();
        const cnt = min + Math.floor(Math.random() * (max - min));
        return shuffled.slice(0, cnt);
    }

    public static randomEle<T>(items: Array<T>): T {
        const idx = Math.floor(Math.random() * items.length)
        return items[idx];
    }

    public static randomInt(from: number, until: number): number {
        return Math.floor(from + Math.random() * until)
    }

}

declare global {
    interface Date {
        format(format: string): string;
    }
}

/** 格式化时间字符串 */
Date.prototype.format = function (format: string): string {
    const year: number = this.getFullYear();
    const month: number = this.getMonth() + 1;
    const day: number = this.getDate();
    const hours: number = this.getHours();
    const minutes: number = this.getMinutes();
    const seconds: number = this.getSeconds();

    return format
        .replace('yy', year.toString())
        .replace('MM', (month < 10 ? '0' : '') + month)
        .replace('dd', (day < 10 ? '0' : '') + day)
        .replace('hh', (hours < 10 ? '0' : '') + hours)
        .replace('mm', (minutes < 10 ? '0' : '') + minutes)
        .replace('ss', (seconds < 10 ? '0' : '') + seconds);
};